//
//  XJHUtils.swift
//  PublicPod
//
//  Created by 许俊华 on 2021/9/3.
//

import UIKit
import CoreTelephony

public class XJHUtils: NSObject {
    // MARK: 获取view当前所在的控制器
    /**
     获取view当前所在的控制器
     */
    public class func getCurrentViewController() -> UIViewController {
        var window = UIApplication.shared.keyWindow
        
        if window?.windowLevel != UIWindow.Level.normal {
            let windows = UIApplication.shared.windows
            for  windowTemp in windows{
                if windowTemp.windowLevel == UIWindow.Level.normal {
                 window = windowTemp
                 break
               }
             }
           }
          let vc = window?.rootViewController
        return currentViewController(vc)!
    }
    
    public class func currentViewController(_ vc :UIViewController?) -> UIViewController? {
       if vc == nil {
          return nil
       }
       if let presentVC = vc?.presentedViewController {
          return currentViewController(presentVC)
       }
       else if let tabVC = vc as? UITabBarController {
          if let selectVC = tabVC.selectedViewController {
              return currentViewController(selectVC)
           }
           return nil
        }
        else if let naiVC = vc as? UINavigationController {
           return currentViewController(naiVC.visibleViewController)
        }
        else {
           return vc
        }
     }
    
    // MARK: 空值判断
    /**
     空值判断
     value 是AnyObject类型是因为有可能所传的值不是String类型，有可能是其他任意的类型。
     */
    public class func isEmpty(value: AnyObject?) -> Bool {
        //首先判断是否为nil
        if (nil == value) {
            //对象是nil，直接认为是空串
            return true
        }else{
            //然后是否可以转化为String
            if let myValue  = value as? String{
                //然后对String做判断
                return myValue == "" || myValue == "(null)" || 0 == myValue.count
            }else{
                //字符串都不是，直接认为是空串
                return true
            }
        }
    }
    
    // MARK: 获取app名称
    /**
     获取app名称
     */
    public class func getAppName() -> String {
        
        let appDisplayName: String = Bundle.main.infoDictionary!["CFBundleDisplayName"] as! String //App 名称
        return appDisplayName
    }
    
    // MARK: 获取app版本号
    /**
     获取app版本号
     */
    public class func getAppVersion() -> String {
        let appVersion:String = Bundle.main.infoDictionary! ["CFBundleShortVersionString"] as! String// App 版本号
        return appVersion
    }
    
    // MARK: 获取app build版号
    /**
     获取app build版号
     */
    public class func getAppBuildVersion() -> String {
        let buildVersion : String = Bundle.main.infoDictionary! ["CFBundleVersion"] as! String
        return buildVersion
    }
    
    // MARK: 获取Bundle Identifier
    /**
     获取Bundle Identifier
     */
    public class func getAppBundleIdentified() -> String {
        let bundleIdentifier:String = Bundle.main.bundleIdentifier!
        return bundleIdentifier
    }
    
    // MARK: 获取设备系统版本iOS版本
    /**
     获取设备系统版本
     */
    public class func getDeviceVersion() -> String {
        let iOSVersion:String = UIDevice.current.systemVersion
        return iOSVersion
    }
    
    // MARK: 获取设备udid
    /**
     获取设备udid
     */
    public class func getDeviceUDID() -> String {
        let identifierNumber:String = UIDevice.current.identifierForVendor!.uuidString
        return identifierNumber
    }
    
    // MARK: 获取设备名称
    /**
     获取设备名称
     */
    public class func getDeviceName() -> String {
        let systemName = UIDevice.current.systemName
        return systemName
    }
    
    // MARK: 获取设备型号
    /**
     获取设备型号
     */
    public class func getDeviceModel() -> String {
        let model = UIDevice.current.model
        return model
    }
    
    // MARK: 获取系统当前语言
    public class func getCurrentLanguage() -> String {
        let userDefault = UserDefaults.standard
        let languages:NSArray = userDefault.object(forKey: "AppleLanguages") as! NSArray
        return languages.object(at: 0) as! String
    }
    
    // MARK: 获取设备机型
    public class func getAppleDeviceModel() -> String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        
        switch identifier {
        case "iPod1,1":  return "iPod Touch 1"
        case "iPod2,1":  return "iPod Touch 2"
        case "iPod3,1":  return "iPod Touch 3"
        case "iPod4,1":  return "iPod Touch 4"
        case "iPod5,1":  return "iPod Touch (5 Gen)"
        case "iPod7,1":   return "iPod Touch 6"
        case "iPod9,1":   return "iPod Touch 6"
            
        case "iPhone3,1", "iPhone3,2", "iPhone3,3":  return "iPhone 4"
        case "iPhone4,1":  return "iPhone 4s"
        case "iPhone5,1":   return "iPhone 5"
        case "iPhone5,2":  return "iPhone 5 (GSM+CDMA)"
        case "iPhone5,3":  return "iPhone 5c (GSM)"
        case "iPhone5,4":  return "iPhone 5c (GSM+CDMA)"
        case "iPhone6,1":  return "iPhone 5s (GSM)"
        case "iPhone6,2":  return "iPhone 5s (GSM+CDMA)"
        case "iPhone7,2":  return "iPhone 6"
        case "iPhone7,1":  return "iPhone 6 Plus"
        case "iPhone8,1":  return "iPhone 6s"
        case "iPhone8,2":  return "iPhone 6s Plus"
        case "iPhone8,4":  return "iPhone SE"
            
        case "iPhone9,1","iPhone9,3":  return "iPhone 7"
        case "iPhone9,2","iPhone9,4":  return "iPhone 7 Plus"
        case "iPhone10,1","iPhone10,4":   return "iPhone 8"
        case "iPhone10,2","iPhone10,5":   return "iPhone 8 Plus"
        case "iPhone10,3","iPhone10,6":   return "iPhone X"
        case "iPhone11,2":  return "iPhone XS"
        case "iPhone11,4","iPhone11,6":  return "iPhone XS Max"
        case "iPhone11,8":  return "iPhone XR"
        case "iPhone12,1":  return "iPhone 11"
        case "iPhone12,5":  return "iPhone 11 Pro Max"
        case "iPhone12,8":  return "iPhone SE2"
        case "iPhone13,1":  return "iPhone 12 mini"
        case "iPhone13,2":  return "iPhone 12"
        case "iPhone13,3":  return "iPhone 12 Pro"
        case "iPhone13,4":  return "iPhone 12 Pro Max"
        case "iPhone14,4":  return "iPhone 13 mini"
        case "iPhone14,5":  return "iPhone 13"
        case "iPhone14,2":  return "iPhone 13 Pro"
        case "iPhone14,3":  return "iPhone 13 Pro Max"
            
        case "iPad1,1":   return "iPad"
        case "iPad1,2":   return "iPad 3G"
        case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":   return "iPad 2"
        case "iPad3,1", "iPad3,2", "iPad3,3":  return "iPad 3"
        case "iPad3,4", "iPad3,5", "iPad3,6":   return "iPad 4"
        case "iPad6,11", "iPad6,12":  return "iPad 5"
        case "iPad7,5", "iPad7,6":  return "iPad 6"
        case "iPad7,11", "iPad7,12":  return "iPad 7"
        case "iPad11,6", "iPad11,7": return "iPad 8"
        case "iPad12,1", "iPad12,2": return "iPad 9"
            
        case "iPad4,1", "iPad4,2", "iPad4,3":   return "iPad Air"
        case "iPad5,3", "iPad5,4":   return "iPad Air 2"
        case "iPad11,3", "iPad11,4": return "iPad Air 3"
        case "iPad13,1", "iPad13,2": return "iPad Air 4"
            
        case "iPad2,5", "iPad2,6", "iPad2,7":  return "iPad Mini"
        case "iPad4,4", "iPad4,5", "iPad4,6":  return "iPad Mini 2"
        case "iPad4,7", "iPad4,8", "iPad4,9":  return "iPad Mini 3"
        case "iPad5,1", "iPad5,2":  return "iPad Mini 4"
        case "iPad11,1", "iPad11,2":  return "iPad Mini 5"
        case "iPad14,1", "iPad14,2":  return "iPad Mini 6"
            
            
        case "iPad6,3", "iPad6,4":  return "iPad Pro 9.7"
        case "iPad6,7", "iPad6,8":  return "iPad Pro 12.9"
        case "iPad7,1", "iPad7,2":   return "iPad Pro2 12.9"
        case "iPad7,3", "iPad7,4":  return "iPad Pro 10.5"
        case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":  return "iPad Pro 11"
        case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":  return "iPad Pro3 12.9"
        case "iPad8,9", "iPad8,10":  return "iPad Pro2 11"
        case "iPad8,11", "iPad8,12":  return "iPad Pro4 12.9"
            
        default:  return identifier
        }
   }
    
    // MARK:获取缓存
    public class func getCacheSize()-> String {

        // 取出cache文件夹目录

        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first

        // 取出文件夹下所有文件数组

        let fileArr = FileManager.default.subpaths(atPath: cachePath!)

        //快速枚举出所有文件名 计算文件大小

        var size = 0

        for file in fileArr! {

            // 把文件名拼接到路径中

            let path = cachePath! + ("/\(file)")

            // 取出文件属性
            let floder = try! FileManager.default.attributesOfItem(atPath: path)

            // 用元组取出文件大小属性

            for (key, fileSize) in floder {

                // 累加文件大小

                if key == FileAttributeKey.size {

                    size += (fileSize as AnyObject).integerValue

                }

            }

        }

        let totalCache = Double(size) / 1024.00 / 1024.00

        return String(format: "%.2fM", totalCache)

    }
    
    // MARK:图片缓存路径
    
    // MARK: 删除APP缓存

    public class func clearCache() {

        // 取出cache文件夹目录

        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first

        let fileArr = FileManager.default.subpaths(atPath: cachePath!)

        // 遍历删除

        for file in fileArr! {

            let path = (cachePath! as NSString).appending("/\(file)")

            if FileManager.default.fileExists(atPath: path) {

                do {

                    try FileManager.default.removeItem(atPath: path)

                } catch {



                }

            }

        }

    }
    
    // MARK:转化为千进制
    public class func convertDoubleToThousands(from:Double) -> String {
        if from > 999.99 {
            return String.init(format: "%.1fk", from / 1000.0)
        } else {
            return "\(String.init(format: "%.2f", from))"
        }
    }
    
    public class func covertIntToThousands(from:Int) -> String {
        if from > 999 {
            return String.init(format: "%.1fk", Double(from) / 1000.0)
        } else {
            return "\(from)"
        }
    }

    
    // MARK:图片转base64
    public class func converUIImageToBase64Str(image:UIImage) -> String {
        
        let imageData:Data = image.jpegData(compressionQuality: 0.5)!
        
        let encodeImageStr:String = imageData.base64EncodedString(options: .lineLength64Characters)

        return encodeImageStr
    }
    
    /**
    view转生成图片
    */
    public class func makeImageWithView(view:UIView, size:CGSize) -> UIImage {
        // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
        UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.main.scale)

        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        
        return image;
    }
    
    /**
     二维码生成
     */
    public class func generateQRCode(str: String) -> UIImage? {
        
        let data = str.data(using: String.Encoding.ascii)
        
        guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
        
        filter.setValue(data, forKey: "inputMessage")
        
        let transform = CGAffineTransform(scaleX: 9, y: 9)
        
        guard let output = filter.outputImage?.transformed(by: transform) else { return nil }
        
        return UIImage(ciImage: output)
    }
    
}
